package info.leetcode.answer.Array.prefix;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 除自身以外数组的乘积
 * @date 2024/3/7 10:51
 */
public class ProductExceptSelf {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4};
        int[] result = productExceptSelf(nums);
        System.out.println(result);
    }

    private static int[] productExceptSelf(int[] nums) {
        List<Integer> prefix = new ArrayList<>();
        prefix.add(nums[0]);
        for (int i = 1; i < nums.length-1; i++) {
            prefix.add(prefix.get(i - 1) * nums[i]);
        }
        List<Integer> suffix = new ArrayList<>();
        suffix.add(nums[nums.length - 1]);
        for (int i = nums.length - 2; i > 0; i--) {
            suffix.add(suffix.get(suffix.size() - 1) * nums[i]);
        }
        int[] result = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            if (i == 0) {
                result[i] = suffix.get(suffix.size() - 1);
                continue;
            }
            if (i == nums.length - 1) {
                result[i] = prefix.get(prefix.size() - 1);
                continue;
            }
            Integer a = prefix.get(i - 1);
            Integer b = suffix.get((suffix.size()-1)- i);
            result[i] = a * b;
        }
        return result;
    }
}
